package com.FOD.fragments;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import com.FOD.clases.R;
import com.FOD.clases.globalFunctions;
import com.FOD.entities.EmpleadoHorario;
import com.FOD.entities.PacienteUsuario;
import com.FOD.entities.User;
import com.FOD.web.UsersFunctions;

public class NewUserPacienteFragment extends Fragment{
	TimePicker inHour;
	TimePicker outHour;
	Button toBackAction;
	EmpleadoHorario mEmpleadoHorario = new EmpleadoHorario(); 
	JSONObject jsonRegisterEmploye = new JSONObject();
	int error = 9;


	View rootView;
	EditText ocupation;
	Spinner civilState;
	CheckBox smocking;
	Spinner studies;
	Spinner bloodType;
	CheckBox alcohol;
	Button addAction;
	User userPrincipalInfo;
	Bundle bundle;
	JSONObject json_user = null;
	JSONObject json;
	UsersFunctions userFunctions = new UsersFunctions();
	PacienteUsuario mPacienteUsuario = new PacienteUsuario();
	ProgressDialog pDialog;
	globalFunctions globalFunctions = new globalFunctions();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.new_user_paciente, container, false);
		inHour = (TimePicker)rootView.findViewById(R.id.timeIn);
		outHour = (TimePicker)rootView.findViewById(R.id.timeOut);
		addAction = (Button)rootView.findViewById(R.id.agregarAction);
		bundle = this.getArguments();


		ocupation = (EditText) rootView.findViewById(R.id.ocupation_new);
		civilState = (Spinner) rootView.findViewById(R.id.civilState_new);
		smocking = (CheckBox) rootView.findViewById(R.id.smoking_new);
		studies = (Spinner) rootView.findViewById(R.id.studies_new);
		bloodType = (Spinner) rootView.findViewById(R.id.bloodType_new);
		alcohol = (CheckBox) rootView.findViewById(R.id.alcohol_new);
		addAction = (Button) rootView.findViewById(R.id.addAction);


		//Asignar valores a Spinners
		ArrayAdapter<CharSequence> adapter_civil_state = ArrayAdapter.createFromResource(rootView.getContext(),R.array.state_civil_spinner, android.R.layout.simple_spinner_item);
		civilState.setAdapter(adapter_civil_state);

		ArrayAdapter<CharSequence> adapter_studies = ArrayAdapter.createFromResource(rootView.getContext(),R.array.studies_spinner, android.R.layout.simple_spinner_item);
		studies.setAdapter(adapter_studies);

		ArrayAdapter<CharSequence> adapter_blood_type = ArrayAdapter.createFromResource(rootView.getContext(),R.array.blood_type_spinner, android.R.layout.simple_spinner_item);
		bloodType.setAdapter(adapter_blood_type);

		addAction.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				userPrincipalInfo = bundle.getParcelable("userToAdd");
				new createUser().execute(userPrincipalInfo);
			}
		}); 

		return rootView;
	}



	private class createUser extends AsyncTask<Object, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Object... params) {
			User userToInsert = (User) params[0];
			return insertUser(userToInsert);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
		}

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(rootView.getContext());
			pDialog.setMessage("Agregando usuario...");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		public Boolean insertUser(User userToInsert){
			json = userFunctions.registerUser(userToInsert);
			try {
				if(json.getInt("error") == 0){
					json_user = json.getJSONObject("user");

					mPacienteUsuario.setUsuario_id(json_user.getInt("id"));
					mPacienteUsuario.setOcupacion(ocupation.getText().toString());
					mPacienteUsuario.setEstadoCivil(mPacienteUsuario.getConverterCivilStatenToInt(civilState.getSelectedItem().toString(), rootView.getContext()));
					mPacienteUsuario.setTabaquismo(((smocking.isEnabled()) ? true:false));
					mPacienteUsuario.setEscolaridad(mPacienteUsuario.getConverterStudiesToInt(studies.getSelectedItem().toString(), rootView.getContext()));
					mPacienteUsuario.setDominancia(bloodType.getSelectedItem().toString());
					mPacienteUsuario.setAlcoholismo(((alcohol.isEnabled()) ? true:false));

					userFunctions.registerPatient(mPacienteUsuario);

					//Delete bundle to save memory
					bundle.remove("userToAdd");
					bundle.clear();

					return true;
				}else{
					return false;
				}



			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (pDialog.isShowing()){
				pDialog.dismiss();
			}
			if(result){
				Toast.makeText(rootView.getContext(), "El usuario se ha agregado con exito", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(rootView.getContext(), "Ocurrio un error al agregar el usuario", Toast.LENGTH_SHORT).show();
			}
			globalFunctions.closeKeyboard(rootView.getContext(), rootView.getWindowToken());
			Fragment fragment = new HomeFragment();
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
		}
	}




	//Hide the keyboard when the Fragmenet is created
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
	}

}
